package user

import (
	"bytes"
	"fmt"
	"github.com/xuri/excelize/v2"
	"io"
	"new_club_recruitment/global"
	"new_club_recruitment/model/user"
	"new_club_recruitment/model/user/request"
)

type UserService struct {
}

//AddUserInfo 添加用户信息
func (u *UserService) AddUserInfo(info user.SysUser) error {
	db := global.GVA_DB
	return db.Create(&info).Error
}

// GetUserInfoList 获取所有的用户信息
func (u *UserService) GetUserInfoList(info request.UserSearch) (list interface{}, total int64, err error) {
	var users []user.SysUser
	var raw string
	db := global.GVA_DB
	if info.Name != "" {
		raw = raw + fmt.Sprintf("user_name like '%%%s%%'", info.Name)
		raw = raw + " or " + fmt.Sprintf("university like '%%%s%%'", info.Name)
		raw = raw + " or " + fmt.Sprintf("college like '%%%s%%'", info.Name)
		raw = raw + " or " + fmt.Sprintf("class_name like '%%%s%%'", info.Name)
		db = db.Where(raw)
	}
	if info.CreateAt != "" {
		db = db.Where(fmt.Sprintf("create_at >= '%s'", info.CreateAt))
	}
	if info.DeadLine != "" {
		db = db.Where(fmt.Sprintf("create_at <= '%s'", info.DeadLine))
	}
	err = db.Model(user.SysUser{}).Count(&total).Error
	if err != nil {
		return
	}
	err = db.Preload("Channel").Limit(info.PageSize).Offset(info.PageSize * (info.PageNum - 1)).Find(&users).Error
	return users, total, err
}

//UpdateUserInfoList 修改用户信息
func (u *UserService) UpdateUserInfoList(info user.SysUser) error {
	db := global.GVA_DB
	return db.Model(&user.SysUser{}).Where("id = ?", info.ID).Updates(&info).Error
}

// GetUserInfo 获取单一报名人员信息
func (u *UserService) GetUserInfo(id string) (data user.SysUser, err error) {
	db := global.GVA_DB
	err = db.Where("id = ?", id).First(&data).Error
	return
}

// ParseInfoList1Excel 打印用户信息
func (u *UserService) ParseInfoList1Excel(infoList []user.SysUser) (file io.ReadSeeker, err error) {
	excel := excelize.NewFile()
	err = excel.SetSheetRow("Sheet1", "A1", &[]string{"ID", "登陆账号", "用户名", "性别", "大学", "学院", "班级", "手机号", "QQ", "报名通道", "选择方向", "内推人"})
	if err != nil {
		return
	}
	for i, menu := range infoList {
		axis := fmt.Sprintf("A%d", i+1)
		err = excel.SetSheetRow("Sheet1", axis, &[]interface{}{
			menu.ID,
			menu.OpenId,
			menu.UserName,
			menu.Sex,
			menu.University,
			menu.College,
			menu.ClassName,
			menu.Phone,
			menu.QQ,
			menu.Channel,
			menu.ClassTo,
			menu.Remarks,
		})
		if err != nil {
			return
		}
	}
	var buffer bytes.Buffer
	err = excel.Write(&buffer)
	file = bytes.NewReader(buffer.Bytes())
	return
}
